package nsqp

import (
	"bgs/conf"
	"bgs/db"
	"bgs/grpc/imp/enums"
	handlers "bgs/nsqp/handlers/runner"
	"bgs/nsqp/util"
	"bgs/nsqp/topic"
	ledgerService "bgs/service/ledger"
	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"
)

const (
	topicOfAddProfitReceiver = "add-profit_receiver"
)

// RunnerProxy proxy run nsq message
type RunnerProxy struct {
	slog     *zap.SugaredLogger
	subs     []*nsq.Consumer
}

// NewRunnerProxy initialization
func NewRunnerProxy(
	nsqConf conf.NsqSection,
	pgdao *db.PgDao,
	slog *zap.SugaredLogger,
	failover *util.NsqFailover,
	ledgerService *ledgerService.LedgerServiceImp,
) (proxy *RunnerProxy, err error) {
	proxy = &RunnerProxy{
		slog: slog,
	}
	config := nsq.NewConfig()

	// addProfitReceiverConsumer
	addProfitReceiverConsumerTopic := topic.Make(enums.APPIDBGS)(topicOfAddProfitReceiver)
	addProfitReceiverConsumer, err := nsq.NewConsumer(addProfitReceiverConsumerTopic, appID, config)
	if err != nil {
		return
	}
	addProfitReceiverConsumer.SetLogger(nsqLogger, nsq.LogLevelError)
	addProfitReceiverConsumer.AddHandler(handlers.NewAddProfitReceiverHandler(pgdao, slog, addProfitReceiverConsumerTopic,
		failover, ledgerService))
	err = addProfitReceiverConsumer.ConnectToNSQLookupd(nsqConf.NsqLookupds[0])
	if err != nil {
		return
	}
	proxy.subs = append(proxy.subs, addProfitReceiverConsumer)

	// Gracefully stop the consumer.
	// consumer.Stop()

	return
}